package tron.oauth.config;

import com.alibaba.fastjson.JSON;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

public class CustomerAccessDecisionManger implements AccessDecisionManager {

    private final RootService rootService;

    public CustomerAccessDecisionManger(RootService rootService) {
        this.rootService = rootService;
    }

    /**
     * 判断当前登录的用户是否具备当前请求URL所需要的角色信息
     * 如果不具备，就抛出 AccessDeniedException 异常，否则不做任何事即可
     *
     * @param authentication 当前登录用户的信息
     * @param o         FilterInvocation对象，可以获取当前请求对象
     * @param collection     FilterInvocationSecurityMetadataSource 中的 getAttributes() 方法的返回值，
     *                       即当前请求URL所需的角色
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        FilterInvocation filterInvocation = (FilterInvocation) o;
        final HttpServletRequest request = filterInvocation.getRequest();
        final String token = request.getHeader("token");
        System.out.printf("----------------当前请求的Token：%s-----------------%n",token);
        // todo 根据请求路径中的Token获取用户
        rootService.getRoleByUser();

        Collection<? extends GrantedAuthority> auths = authentication.getAuthorities();

        for (ConfigAttribute configAttribute : collection) {
            System.out.println("-----当前资源需要权限：-----> " + configAttribute.getAttribute());
            System.out.println("-----当前用户拥有权限：-----> " + JSON.toJSONString(auths));
			/*
			  如果需要的角色是ROLE_ANONYMOUS，说明当前请求的URL用户登陆后即可访问；
			  如果authentication是UsernamePasswordAuthenticationToken实例，说明当前用户已登录。
			 */
            if ("ROLE_ANONYMOUS".equals(configAttribute.getAttribute()) &&
                    authentication instanceof UsernamePasswordAuthenticationToken) {
                return;
            }
            for (GrantedAuthority authority : auths) {
                if (configAttribute.getAttribute().equals(authority.getAuthority())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足！");
    }

    /**
     * 是否支持校验
     */
    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }


    /**
     * 是否支持校验
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
